import { useEffect, useState } from 'react';
import { Button, Table, Modal, message } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { ExclamationCircleFilled } from '@ant-design/icons';
import { getSearchModal, getSelectionMemberModal } from '../servers';
import { useSafeState } from 'ahooks';
import { getMessage, TextWidget } from '@inbiz/react';
import MemberSelect from '@inbiz/basic/MemberSelect';
import { getUserInfo } from '@inbiz/utils';
interface ModalSearchListProps {
  currentIncidentID: string;
  setExamine: Function;
}
const { confirm } = Modal;
const ModalSearchList = (props: ModalSearchListProps) => {
  const { currentIncidentID, setExamine } = props;
  const [searchModalList, setSearchModalList] = useState([]);
  const [Selected, setSelected] = useState<searchType[]>([]);
  const [TaskID, setTaskID] = useSafeState([]);
  const [membervisible, setmembervisible] = useState(false);
  const AreYouSureYouWantToAssignTheCurrentTaskTo = getMessage(
    'ProcessMonitoring.AreYouSureYouWantToAssignTheCurrentTaskTo',
  );
  const userInfo = getUserInfo()
  //调用当前审核人数据
  useEffect(() => {
    if (currentIncidentID) {
      getSearchModal(currentIncidentID).then((res: any) => {
        if (res?.code == 200 && res?.details) {
          let result = res.details.rows;
          result = result?.filter(
            (item: { AssigneeUserID: any }) => item?.AssigneeUserID,
          );
          setSearchModalList(result);
        } else {
          setSearchModalList([]);
        }
      });
    }
  }, [currentIncidentID]);

  //查找当前审核人弹窗列数据类型
  interface searchType {
    AssigneeUserName: string;
    delegateUserId: string;
    handelUserId: string;
    singleMandate: boolean;
    taskIds: string;
    AssigneeUserAccount: string;
    AssigneeUserID: string;
    ProcessID: string;
    TaskDefId: string;
    TaskID: string;
    TaskName: string;
  }
  //查找当前审核人弹窗列
  const columnsSearch: ColumnsType<searchType> = [
    {
      title: getMessage('ProcessMonitoring.AssigneeUserName'), //审批人
      dataIndex: 'AssigneeUserName',
      key: 'AssigneeUserName',
      render: (text) => <span>{text}</span>,
    },
  ];

  //指派弹窗
  const designate = () => {
    if (Selected && Selected?.length) {
      setmembervisible(true);
    } else {
      message.info(getMessage('ProcessMonitoring.pleaseSelectARecord')); //请选择记录
    }
  };

  //指派
  const dodesignate = (rows: any) => {
    if (rows && rows?.length) {
      let result = rows;
      confirm({
        title: `${AreYouSureYouWantToAssignTheCurrentTaskTo} ${result
          ?.map((item: any) => item?.name)
          ?.join(',')}(${result[0].userloginname})?`,
        icon: <ExclamationCircleFilled />,
        centered: true,
        okText: getMessage('ProcessMonitoring.determine'), //确定
        cancelText: getMessage('ProcessMonitoring.cancel'), //取消
        onOk() {
          getSelectionMemberModal({
            delegateUserId: rows?.map((item: any) => item?.id)?.join(','),
            handelUserId: userInfo.guid,
            taskIds: Selected[0].TaskID,
          }).then((res: any) => {
            if (res?.code == 200) {
              message.success(
                getMessage('ProcessMonitoring.assignmentSucceeded'),
              ), //指派成功
                setSelected([]);
              getSearchModal(currentIncidentID).then((res: any) => {
                if (res?.code == 200 && res?.details) {
                  let _result = res.details.rows;
                  setSearchModalList(_result);
                } else {
                  setSearchModalList([]);
                }
              });
              setExamine(false);
              getSearchModal(currentIncidentID);
            } else {
              message.error(getMessage('ProcessMonitoring.assignmentFailed')); //指派失败
            }
            setmembervisible(false);
          });
        },
        onCancel() {
          setExamine(true);
        },
      });
    } else {
      message.info(getMessage('ProcessMonitoring.valueCannotBeEmpty')); //值不能为空
    }
  };

  //修改被选中表格样式
  const setRowClassName = (record: any) => {
    return record.TaskID == TaskID ? 'clickAssignStyle' : '';
  };
  return (
    <>
      <div className="currentAssignToolbar">
        <div className="current-btn">
          <Button
            type="primary"
            onClick={designate}
            style={{
              margin: '0 0 10px 0',
            }}
          >
            {/* 指派 */}
            <TextWidget>ProcessMonitoring.assign</TextWidget>
          </Button>
        </div>
        <div className="currentAssignToolbarTable">
          <Table
            scroll={{ y: 180 }}
            bordered={true}
            pagination={false}
            columns={columnsSearch}
            size="small"
            dataSource={searchModalList}
            showHeader={true}
            rowClassName={setRowClassName}
            onRow={(record: any) => {
              return {
                onClick: (event) => {
                  // 点击行
                  setSelected([record]);
                  setTaskID(record.TaskID);
                },
              };
            }}
          />
        </div>
        <MemberSelect
          visible={membervisible}
          config={{
            tabs: ['user'],
            multiple: false, //控制单选
            onCancel: () => {
              setmembervisible(false);
            },
            onOk: (keys, rows) => {
              dodesignate(rows);
            },
          }}
        />
      </div>
    </>
  );
};

export default ModalSearchList;
